//
//  game.c
//  Mine Sweeper
//
//  Created by Daniel on 2024/5/22.
//

#include "game.h"

void InitBoard(char board[COLUMNS][ROWS],int rows,int columns,char set)
{
    for (int i = 0; i<=rows; i++) {
        for (int j = 0; j<=columns; j++) {
            board[i][j] = set;
        }
        
    }
}

void DisplayBoard(char board[ROWS][COLUMNS],int row,int colum)
{
    printf("-------扫雷游戏------\n");
    for (int i = 0; i <= colum; i++) {
        printf("%d ",i);
    }
    printf("\n");
    for (int i = 1; i <= row; i++) {
        printf("%d ",i);
        for(int j = 1; j <= colum; j++)
        {
            printf("%c ",board[i][j]);
        }
        printf("\n");
    }
    printf("-------扫雷游戏-------\n");
}
void SetMine(char board[ROWS][COLUMNS],int row,int column)
{
    int count = EASY_COUNT;
    while (count) {
        int x = rand() % row + 1;//1~9
        int y = rand() % column + 1;
        if(board[x][y] == '0')
        {
            board[x][y] = '1';
            count--;
        }
    }
}

void FindMine(char mine[ROWS][COLUMNS],char show[ROWS][COLUMNS],int row,int column)
{
    int x = 0;
    int y = 0;
    int not_mine = 0;
    while (not_mine < row * column - EASY_COUNT) {
        printf("请输入要排查的坐标:>");
        scanf("%d %d",&x, &y);
        if(x >= 1 && x <= row && y >= 1 && y <= column)
        {
            if(show[x][y] != '*')
            {
                printf("该坐标重复输入，请输入其他坐标\n");
            }else
            {
                //            如果是雷
                if(mine[x][y] == '1')
                {
                    printf("很遗憾，您被炸死了\n");
                    DisplayBoard(mine, ROW,COLUMN);
                    break;
                    //          如果不是雷
                }else
                {
                    not_mine++;
                    int count = get_mine_count(mine, x, y);
                    show[x][y] = count + '0';//转换成字符
                    DisplayBoard(show, ROW, COLUMN);
                    
                }
            }
            
        }else
        {
            printf("输入的坐标超出范围，请重新输入⬇️\n");
        }
    }
    //    游戏胜利
    if(not_mine == row * column - EASY_COUNT)
    {
        printf("恭喜您，游戏通关\n");
        DisplayBoard(mine, ROW, COLUMN);
    }
}

int get_mine_count(char board[ROWS][COLUMNS],int  x,int y)
{
    int num = 0;
    for (int i = -1; i < 1; i++)
    {
        for (int j = -1; j < 1; j++) {
            num = num + board[x+i][y+j] - '0';
//            Extend()
//            int x = 0;
//            int y = 0;
//            int not_mine = 0;
//            while (not_mine < row * column - EASY_COUNT) {
//
//                scanf("%d %d",&x, &y);
//            FindMine(mine,show,int row,int column);
        }
    }
    return num;
    //    相当于
//        return board[x-1][y-1]+board[x-1][y]+board[x-1][y+1]+board[x][y-1]+board[x][y+1]+board[x+1][y-1]+board[x+1][y]+board[x+1][y+1] - 8 * '0';
}

void Extend(char mine[ROWS][COLUMNS],char show[ROWS][COLUMNS],int row,int column);
